"""
socket handle and info handle
"""
import sys
import socket
import sqlite3
from datetime import datetime

def createServer(port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error as msg:
        print("socket creat error:", msg)
        sys.exit()
    try:
        sock.bind(('',port))
    except socket.error as msg:
        print("bind error:", msg)
        sock.close()
        sys.exit()
    sock.listen(10)
    print("serv sock ok:", sock)
    return sock

def parseData(data):
    # parse the info string like ;
    #“to:George,bruce;from:John;head:alarm-xxx;body:meeting!;size:10240;path:image.jpg”
    c = data
    info = {}
    while c != '':
        a, b, c = c.partition(';')
        h, i, j = a.partition(':')
        info[h] = j
    to_list = info['to'].replace(',', ';')
    file_size = int(info['size'])
    info['to'] = to_list
    info['size'] = file_size
    print ("email info:", info)
    return info

def updateDBInfo(info, result):
    db = sqlite3.connect("sendemail.db")
    dbc = db.cursor()
    record = (info['id'], info['from'], info['to'], info['head'], info['body'],
                        info['size'], info['path'], result,datetime.now().isoformat(' '))
    dbc.execute("create table if not exists mailrec "
    "([id] integer primary key autoincrement,[did] varchar(10) not null,"
    "[from] varchar(64),[to] varchar(512),[head] varchar(512),"
    "[body] varchar(512),[size] integer,[path] varchar(64),"
    "[result] varchar(64),[time] varchar(64))")
    dbc.execute("insert into mailrec values(NULL,?,?,?,?,?,?,?,?,?)", record)
    db.commit()
    db.close()

if __name__ == "__main__":
    info = parseData("to:George,bruce;from:John;head:alarm-xxx;body:meeting!;size:10240;path:image.jpg")
    #print(info)


